<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="1136px"
      title="邀请专家"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <div class="search-container">
          <div class="item">
            <a-input
              placeholder="请输入专家姓名"
              v-model.trim="condition.expertName"
              allowClear
              style="width: 160px"
            />
          </div>
          <div class="item">
            <a-select
              showSearch
              allowClear
              style="width: 160px"
              :filter-option="filterOption"
              placeholder="请选择专业"
              v-model="condition.professionType"
              :loading="condition.professionLoading"
              @change="search()"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in condition.professionSource"
                :key="item.uuid"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
          </div>
          <div>
            <a-button type="primary" @click="search()"> 查询 </a-button>
          </div>
        </div>
        <div class="info-container">
          已选择<span class="num">{{ exportTotal }}</span
          >项 <span class="clear"></span>
        </div>
        <div class="table-container">
          <vxe-table
            ref="xTable"
            min-height="400px"
            align="center"
            show-overflow
            show-header-overflow
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="loading"
          >
            <vxe-column width="60">
              <template #header>
                <a-checkbox
                  v-model="allcChecked"
                  :indeterminate="indeterminate"
                  @change="allClick($event)"
                >
                </a-checkbox>
              </template>
              <template #default="{ row }">
                <a-checkbox
                  v-model="row.check"
                  @change="changeItem($event, row)"
                >
                </a-checkbox>
              </template>
            </vxe-column>
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column field="expertName" title="专家姓名"> </vxe-column>
            <vxe-column field="mobile" title="联系方式"> </vxe-column>
            <vxe-column field="professionName" title="专业"> </vxe-column>
          </vxe-table>
        </div>
        <div class="pager-container">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条记录
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button
          type="primary"
          :disabled="checkRowKeys.length > 0 ? false : true"
          @click="onSubmit()"
          :loading="buttonLoading"
        >
          确定
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
export default {
  name: "inviteModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getMajorList();
          this.getDetail();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      condition: {
        //专家姓名
        expertName: "",
        //专业
        professionType: undefined,
        professionSource: [],
        professionLoading: false,
      },
      //表格
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      buttonLoading: false,
      //选择人员
      checkRowKeys: [],
      checkList: [],
      userList: [],
      allcChecked: false,
      indeterminate: false,
      exportTotal: 0,
    };
  },
  methods: {
    onSubmit() {
      this.buttonLoading = true;
      let { uuid, tenantCode } = this.parameter;
      let { checkRowKeys } = this;
      let formJson = {
        evaluationId: uuid,
        configExpertIds: checkRowKeys.toString(),
        tenantCode,
      };
      axios
        .post(`/probusiness/qeProjectExpert/saveExpertData`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.closeModal();
            this.$parent.getData();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.buttonLoading = false;
        });
    },

    //查看专家
    getDetail() {
      let { uuid, tenantCode } = this.parameter;
      axios
        .post(
          `/probusiness/qeProjectExpert/getExpertList`,
          {
            evaluationId: uuid,
            tenantCode,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.userList = data || [];
        })
        .catch((_) => {
          this.userList = [];
        })
        .finally((_) => {
          this.getTableData();
        });
    },

    //全选
    allClick(e) {
      this.indeterminate = false;
      let ev = this.allcChecked;
      if (ev) {
        this.tableData.forEach((v) => {
          this.$set(v, "check", true);
        });
      } else {
        this.tableData.forEach((v) => {
          this.$set(v, "check", false);
        });
      }
      let ids = [];
      this.tableData.forEach((v) => {
        if (v.check) {
          ids.push(v.uuid);
          if (this.checkList.indexOf(v.uuid) == -1) {
            this.checkList.push(v.uuid);
          }
        } else {
          var _index = this.checkList.indexOf(v.uuid);
          if (_index != -1) {
            this.checkList.splice(_index, 1);
          }
        }
      });

      this.checkRowKeys = this.checkList;
      this.exportTotal = this.checkRowKeys.length;
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let ids = [];
      try {
        this.tableData.forEach((v) => {
          if (v.check) {
            throw v;
          }
        });
        this.indeterminate = false;
      } catch (error) {
        this.indeterminate = true;
      }
      this.tableData.forEach((key) => {
        if (key.check) {
          ids.push(key.uuid);
          if (this.checkList.indexOf(key.uuid) == -1) {
            this.checkList.push(key.uuid);
          }
        }
      });
      if (ids.length == this.tableData.length) {
        this.indeterminate = false;
        this.allcChecked = true;
      } else {
        this.allcChecked = false;
      }
      if (!checked) {
        var _index = this.checkList.indexOf(row.uuid);
        if (_index != -1) {
          this.checkList.splice(_index, 1);
        }
      }

      this.checkRowKeys = this.checkList;
      this.exportTotal = this.checkRowKeys.length;
    },

    //查询
    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    //查询专业
    getMajorList() {
      this.condition.professionLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "professionType",
        })
          .then((res) => {
            let { data } = res;
            this.condition.professionSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.condition.professionSource = [];
            reject();
          })
          .finally((_) => {
            this.condition.professionLoading = false;
          });
      });
    },
    //查询列表
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { professionType = "", expertName = "" } = this.condition;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/configExpert/getPageSet?pageNo=${page}&pageSize=${pageSize}`,
            {
              professionType,
              expertName,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.tableData = res?.rows ?? [];
            this.pager.total = res?.totalCount ?? 0;
            if (this.tableData.length == 0) {
              this.checkRowKeys = [];
              this.indeterminate = false;
              return;
            }
            //判断查询已选人员
            this.checkRowKeys = [];
            this.tableData.forEach((item) => {
              this.userList.forEach((v) => {
                if (item.expertName == v.expertName) {
                  this.checkRowKeys.push(item.uuid);
                }
              });
            });
            this.tableData.forEach((item) => {
              this.$set(item, "check", false);
              this.checkRowKeys.forEach((v) => {
                if (item.uuid == v) {
                  this.$set(item, "check", true);
                }
              });
            });

            this.exportTotal = this.checkRowKeys.length;

            let ids = [];
            try {
              this.tableData.forEach((v) => {
                if (v.check) {
                  throw v;
                }
              });
              this.indeterminate = false;
            } catch (error) {
              this.indeterminate = true;
            }
            this.tableData.forEach((v) => {
              if (v.check) {
                ids.push(v);
              }
            });
            if (ids.length == this.tableData.length) {
              this.indeterminate = false;
              this.allcChecked = true;
            } else {
              this.allcChecked = false;
            }

            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            this.checkList = [];
            this.checkRowKeys = [];
            this.allcChecked = false;
            this.indeterminate = false;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //关闭弹窗
    closeModal() {
      this.condition.expertName = "";
      this.condition.professionType = undefined;
      this.checkRowKeys = [];
      this.checkList = [];
      this.userList = [];
      this.allcChecked = false;
      this.indeterminate = false;
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .ant-modal-header {
    position: relative;
    .ant-modal-title {
      &::before {
        content: "";
        position: absolute;
        top: 18px;
        left: 10px;
        background-color: @primary-color;
        height: 17px;
        width: 5px;
      }
    }
  }

  .curve-modal-body {
    padding: 14px;
    max-height: 700px;
    display: flex;
    flex-direction: column;
    .search-container {
      display: flex;
      align-items: center;
      .item {
        margin-right: 16px;
      }
    }
    .info-container {
      margin: 10px 0;
      height: 44px;
      background: rgba(0, 152, 255, 0.1);
      border: 1px solid #5ebcfb;
      font-size: 16px;
      color: #0098ff;
      display: flex;
      align-items: center;
      padding: 0 24px;
      .num {
        margin: 0 4px;
        font-weight: 700;
      }
      .clear {
        margin-left: 20px;
        cursor: pointer;
      }
    }
    .table-container {
      flex: 1;
      height: 100%;
    }
    .pager-container {
      padding-top: 10px;
      flex-shrink: 0;
    }
  }
  .curve-modal-footer {
    padding: 10px 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    border-radius: 0 0 4px 4px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 150px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
}
</style>
